<?php
// +---------------------------------------------------------------------------+
// | This file is part of the KnowledgebasePublisher package                   |
// | KnowledgebasePublisher - web based knowledgebase publisher tool           |
// |                                                                           |
// | Author:  Evgeny Leontev <eleontev@gmail.com>                              |
// | Copyright (c) 2005 Evgeny Leontev                                         |
// |                                                                           |
// | For the full copyright and license information, please view the LICENSE   |
// | file that was distributed with this source code.                          |
// +---------------------------------------------------------------------------+

require_once 'core/app/DataToValueModel.php';
require_once 'core/common/CommonEntryModel.php';


class FileEntryModel extends CommonEntryModel
{
	var $tbl_pref_custom = 'file_';
	var $tables = array('table'=>'entry', 'entry', 'category', 'entry_to_category', 'data', 'text');
	var $custom_tables = array('kb_attachment_to_entry', 'role');
	
	var $id_field = 'id';
	var $setting = array();
	//var $file_to_read;
	var $member_rore_rule = 'file_entry_to_member_role';
	
	
	function FileEntryModel() {
		parent::CommonEntryModel();
		$this->dv_manager = &new DataToValueModel();
	}	
	
	
	function getById($record_id) {
		$sql = "SELECT e.* FROM {$this->tbl->entry} e WHERE e.id = '$record_id'";
		$result =& $this->db->Execute($sql) or die(db_error($sql));
		return $result->FetchRow();
	}
	
	
	function setFileSetting(&$values) {
		
		$this->setting = &$values;
		$this->setting['file_denied_extensions'] = ($this->setting['file_denied_extensions']) 
		                                        ? explode(',', $this->setting['file_denied_extensions'])
												: array();
												
		$this->setting['file_allowed_extensions'] = ($this->setting['file_allowed_extensions']) 
		                                        ? explode(',', $this->setting['file_allowed_extensions'])
												: array();
	}
	
	
	function getRecordsSql() {
		
		$sql = "
		SELECT 
			e.id,
			e.filename,
			e.title,
			e.filesize,
			e.filetype,
			e.downloads,
			e.private,
			e.active,
			IF(e.filetext = '', 0, 1) as filetext,
			cat.id AS category_id,
			cat.name AS category_name,
			cat.private AS category_private,
			UNIX_TIMESTAMP(e.date_posted) AS ts
			
		FROM 
			{$this->tbl->entry} e,
			{$this->tbl->category} cat,
			{$this->tbl->entry_to_category} e_to_cat
		WHERE 1
			AND e.id = e_to_cat.entry_id
			AND cat.id = e_to_cat.category_id
			AND {$this->sql_params}
		GROUP BY e.id
		{$this->sql_params_order}";
		
		//echo "<pre>"; print_r($sql); echo "</pre>";
		return $sql;
	}		
	
	
	function &getFileText($file_id) {
		$sql = "SELECT filetext FROM {$this->tbl->table} WHERE id = %d";
		$sql = sprintf($sql, $file_id);
		$result =& $this->db->Execute($sql) or die(db_error($sql));
		return $result->Fields('filetext');		
	}
	
	
	// for page by page
	function getCountRecordsSql() {
		$sql = "SELECT COUNT(DISTINCT(e.id)) 
		FROM 
			{$this->tbl->entry} e,
			{$this->tbl->category} cat,
			{$this->tbl->entry_to_category} e_to_cat	
		WHERE e.id = e_to_cat.entry_id
		AND cat.id = e_to_cat.category_id
		AND {$this->sql_params}";
		return $sql;
	}	
	
	
	// CATEGORIES // ---------------------------	
	
	function getCategoryRecords() {
		$this->cat = new FileCategoryModel();
		return $this->cat->getSelectRecords();
	}		
	
	
	// ACTIONS // ---------------------
		
	function saveEntryToCategory(&$obj, $record_id) {
		
		require_once 'eleontev/SQL/MultiInsert.php';
		
		foreach($obj->getCategory() as $k => $v) {
			$categories[] = array($v, 1);
		}
		
		foreach($obj->getCategoryMirror() as $k => $v) {
			$categories[] = array($v, 0);
		}		
		
		$sql = MultiInsert::get("INSERT IGNORE {$this->tbl->entry_to_category} (category_id, is_main, entry_id) 
		                         VALUES ?", $categories, array($record_id));
		
		return $this->db->Execute($sql) or die(db_error($sql));
	}

	
	function updateFileText($filetext, $file_id) {
		$sql = "UPDATE {$this->tbl->table} SET 
		filetext = '{$filetext}'
		WHERE id = '{$file_id}'";
		$result = &$this->db->Execute($sql) or die(db_error($sql));
	}
	
	
	function countDownload($file_id) {
		$sql = "UPDATE {$this->tbl->table} SET 
		downloads = downloads+1, 
		date_updated=date_updated
		WHERE id = '{$file_id}'";
		$result = &$this->db->Execute($sql) or die(db_error($sql));
	}
	
	
	// PRIV // ------------------------------	
	
	// if check priv is different for model so reassign 	
	function checkPriv(&$priv, $action, $record_id, $popup = false) {
		
		$priv->setCustomAction('text', 'update');
		$priv->setCustomAction('file', 'select');
		$priv->setCustomAction('bulkadd', 'update');
		
		if($priv->getPrivId() == 5) {
			$sql = "SELECT 1 FROM {$this->tbl->table}  
			WHERE id = '{$record_id}' 
			AND author_id = {$priv->user_id}
			AND updater_id = {$priv->user_id}";
		} else {
			$sql = "SELECT 1 FROM {$this->tbl->table}  
			WHERE id = '{$record_id}' AND author_id = {$priv->user_id}";			
		}
		
		$priv->setOwnSql($sql);
		$priv->check($action);
		
		// set sql to select own records
		if($popup) { $priv->setOwnParam(1); } // to display all in popup
		else       { $priv->setOwnParam(sprintf("author_id=%d", $priv->user_id)); }
		
		$this->setSqlParams('AND ' . $priv->getOwnParam());
	}
		
	
	// DELETE RELATED // --------------------- 
	
	function isEntryInUse($entry_id) {
		$sql = "SELECT COUNT(*) as num FROM {$this->tbl->kb_attachment_to_entry} 
		WHERE attachment_id = '{$entry_id}'";
		$result = &$this->db->Execute($sql) or die(db_error($sql));
		return $result->Fields('num');
	}
	
	function deleteEntries($record_id) {
		$sql = "DELETE FROM {$this->tbl->entry} WHERE id IN ({$record_id})";
		return $this->db->Execute($sql) or die(db_error($sql));
	}
	
	function deleteEntryToCategory($record_id) {
		$sql = "DELETE FROM {$this->tbl->entry_to_category} WHERE entry_id IN ({$record_id})";
		return $this->db->Execute($sql) or die(db_error($sql));
	}
	
	function delete($record_id, $from_disk) {
		
		// convert to string 1,2,3... to use in IN()
		$record_id = $this->idToString($record_id);
		
		$this->deleteFileData($record_id, $from_disk);
		$this->deleteEntries($record_id);
		$this->deleteEntryToCategory($record_id);
		
		if($this->isExtra('private')) {
			$this->deleteMemberRoleToEntry($record_id);
		}		
	}
}
?>